
// Definition for a binary tree node.
function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
}

/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
  if(root == null || root.val == p || root.val == q) {
    return root;
  }
  let left = lowestCommonAncestor(root.left, p, q);
  let right = lowestCommonAncestor(root.right, p, q);
  if(left == null) return right;
  if(right == null) return left;
  return root;
};
let root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1;
console.log(lowestCommonAncestor(root, p, q));
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4;
console.log(lowestCommonAncestor(root, p, q));
root = [1,2], p = 1, q = 2;
console.log(lowestCommonAncestor(root, p, q));
